#include "comm.h"

void Usage(char* proc){
    std::cout << "Usage:\n\t" << proc << " proc.addr" << " proc.port" << std::endl;
}

int main(int argc, char* argv[]){
    if (argc != 3){
        Usage(argv[0]);
        return -1;
    }
    uint16_t port = atoi(argv[2]);
    std::string svr_ip = argv[1];

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0){
        std::cerr << "sock failed" << errno << std::endl;
        return 1;
    }
    std::cout << "socket success" << std::endl;

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    //server.sin_addr.s_addr = inet_addr(svr_ip.c_str());
    server.sin_addr.s_addr = INADDR_ANY;
    if (connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0){
        std::cout << "connect failed" << std::endl;
        return 2;
    }
    std::cout << "链接成功" << std::endl;

    while (true){
        std::cout << "请输入指令:>";
        char command[1024] = {0};
        fgets(command, sizeof(command) - 1, stdin);

        write(sock, command, strlen(command));
        char ret[1024] = {0};
        ssize_t size = read(sock, ret, sizeof(ret));
        if (size > 0){
            ret[size] = 0;
            std::cout << "server say:" << ret << std::endl;
        }
        else if (size == 0){
            continue;
        }
    }
 
}